package com.sunyu.springboot.config;

import com.sunyu.springboot.component.RestTemplateClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLContext;

/**
 * @author yu 2018/12/20.
 */
@Configuration
public class RestTemplateClientConfig {

    /**
     * 兼容http和https
     *
     * @return
     * @throws Exception
     */
    @Bean
    public RestTemplateClient restTemplateClient() throws Exception {

        SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(new TrustSelfSignedStrategy()).build();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLContext(sslContext)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setConnectTimeout(2000);
        requestFactory.setReadTimeout(2000);
        RestTemplateClient restTemplate = new RestTemplateClient(requestFactory);
        ((HttpComponentsClientHttpRequestFactory) restTemplate
                .getRequestFactory()).setHttpClient(httpClient);
        return restTemplate;
    }
}
